package _interview100;

import _object.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 114. 二叉树展开为链表
 */
public class No114 {
    private Queue<TreeNode> queue;

    /**
     * 1. 前序遍历
     */
    public void flatten(TreeNode root) {
        if (root == null) return;
        queue = new LinkedList<>();
        dfs(root);
        root = queue.poll();
        root.left = null;
        while (!queue.isEmpty()) {
            TreeNode poll = queue.poll();
            poll.left = null;
            poll.right = null;
            root.right = poll;
            root = root.right;
        }
    }

    private void dfs(TreeNode node) {
        if (node == null) return;
        queue.add(node);
        dfs(node.left);
        dfs(node.right);
    }

    /**
     * 2.1 原地修改（递归）
     */
    public void flatten21(TreeNode root) {
        dfs2(root);
    }

    private TreeNode dfs2(TreeNode node) {
        if (node == null || (node.left == null && node.right == null)) return node;
        TreeNode leftNode = dfs2(node.left);
        TreeNode rightNode = dfs2(node.right);
        if (leftNode != null) {
            leftNode.right = node.right;
            node.right = node.left;
            node.left = null;
        }
        return rightNode == null ? leftNode : rightNode;
    }

    /**
     * 2.2 原地修改（迭代）
     */
    public void flatten22(TreeNode root) {
        while (root != null) {
            TreeNode leftNode = root.left;
            while (leftNode != null && leftNode.right != null) {
                leftNode = leftNode.right;
            }
            if (leftNode != null) {
                leftNode.right = root.right;
                root.right = root.left;
                root.left = null;
            }
            root = root.right;
        }
    }
}
